
import { inject } from 'vue'
import useCheck from './useCheck'
import api from '../../../api/search'

export default function useCopy() {
  const ref_table = inject('ref_table')

  const {
    checkParams,
    checkLogin,
    checkOther,
    beforeCopyConfirm,
    afterCopyConfirm,
  } = useCheck()

  const checkBeforeCopy = async (confirm, confirmHandler, cancelHandler) => {
    try {
      await checkParams()
      await checkLogin()
      await checkOther()
    } catch (err) {
      throw new Error(err.message)
    }

    try {
      await beforeCopyConfirm(confirm, confirmHandler, cancelHandler)
    } catch (err) {
      throw new Error(err.message)
    }

    return 'resolve'
  }

  const handleCopy = (type, row) => {
    try {
      await checkBeforeCopy({
        title: type,
        confirmText: '确定',
        cancelText: '取消',
      })
    } catch (err) {
      console.log(err.message)
      return
    }

    const { data, selection, page_size } = ref_table.value
    let urls = ''

    switch(type) {
      case 'all': 
        urls = data.map(v => v.url).join('\r')
        break
      case 'selected':
        urls = selection.map(v => v.url).join('\r')
        break
      case 'page':
        urls = data.slice(0, page_size).map(v => v.url).join('\r')
        break
      case 'current':
        urls = row.url
        break
    }

    try {
      const res = await api.copy({ urls })
      console.log(res.msg)
    } catch (err) {
      console.log(err.message)
      return
    }

    afterCopyConfirm(
      {
        title: '复制成功',
        confirmText: '确定',
        cancelText: '取消',
      },
      () => {
        // router.push('/copy/record')
      },
    )
  }

  return {
    handleCopy,
  }
}